<template>
  <div class="login-stats">
    <!-- 左侧统计卡片 -->
    <div class="stat-cardleft left">
      <h3>园区全景</h3>
      <span style="position: fixed ;cursor: pointer;color:red;margin-top: -45px;margin-left: 120px;"
        @click="fullIframe">
        <el-icon class="icon-calendar">
          <FullScreen />
        </el-icon>
      </span>
      <div class="stat-item">
        <iframe ref="sevenTwoZeroIframe" :src="iframeSource" frameborder="no" style=" width: 100%;max-height: 100%;"></iframe>
      </div>
      <h3>园区视频</h3>
      <div class="stat-item">
        <video class="video-player" ref="videoPlayer" autoplay muted playsinline loop :src="videoSource" controls
          style="width: 265px;">
          您的浏览器不支持HTML5视频播放
        </video>
      </div>
      <h3>关注企业</h3>
      <el-scrollbar style="height: 160px;" class="elScroll">
        <ul v-for="(comp, index) in enterpriseData" :key="index" @click="handleItemClick(comp, index)"
          style="cursor: pointer; padding: 4px 0;">
          <li>
            {{ index + 1 }}. {{ comp.enterpriseName }}
          </li>
        </ul>
      </el-scrollbar>
    </div>

    <!-- 右侧统计卡片 -->
    <div class="stat-cardright right">
      <h3>企业入驻情况</h3>
      <div class="stat-item" style="color: gray;">
        <span>入驻企业（审核中）：</span>
        <span class="value">{{ kpiData.enterprisePendingTotal }} 家</span>
        <!-- <span class="value">3 家</span> -->
      </div>
      <div class="stat-item" style="color: green;">
        <span>入驻企业（已入住）：</span>
        <span class="value">{{ kpiData.enterpriseApprovedTotal }} 家</span>
        <!-- <span class="value">128 家</span> -->
      </div>
      <div class="stat-item" style="color: red;">
        <span>入驻企业（已离园）：</span>
        <span class="value">{{ kpiData.enterpriseMovedOutTotal }}家</span>
        <!-- <span class="value">3家</span> -->
      </div>
      <div class="stat-item">
        <span>房间使用率：</span>
        <span class="value"> {{ kpiData.spaceRate }}%</span>
        <!-- <span class="value"> 70.8%</span> -->
      </div>
      <h3>园区入住企业统计</h3>
      <div class="chart-container" style="margin-top: -40px;">
        <div ref="occupancyChart" class="chart"></div>
      </div>
      <h3>园区空间使用效率</h3>
      <div class="chart-container">
        <div ref="spaceUsageChart" class="chart"></div>
      </div>
    </div>
  </div>

  <!-- 查看弹框 -->
  <EnterpriseViewPage :visible="viewPageVisible" :enterprise="currentEnterprise" @close="handleViewPageClose" />
</template>

<script setup>

import { ref, onMounted,computed,nextTick } from 'vue';
import * as echarts from 'echarts';
import request from '@/api/request'
import { ElMessage, ElLoading } from 'element-plus';
import EnterpriseViewPage from '../../manage/datamanage/enterprise/viewpage/EnterpriseViewPage.vue';
import auth from '@/components/utils/auth'

/**
 * 静态视频地址
 */
const videoPlayer = ref(null);
// 视频和 iframe 源
const videoSource = ref('');
const iframeSource = ref('');

// 构建资源 URL
const buildVideoUrl = (userId) => {
  const baseUrl = import.meta.env.VITE_BASE_MODEL_URL;
  if (userId==2) {
    return `${baseUrl}/static-file/fhy.mp4`;
  }
  return `${baseUrl}/lps/pb.mp4`;
};

const buildIframeUrl = (userId) => {
  if (userId==2) {
    return `https://www.720yun.com/vr/84bjt5syuw0`;
  }
  return `https://roma.720yun.com/vr/6f9770ca990fefec`;
};
// 更新资源
const updateResources = async () => {
  const currentUserId = userId.value;
  
  console.log('更新资源，用户ID:', currentUserId);
  
  // 更新视频源
  const newVideoUrl = buildVideoUrl(currentUserId);
  videoSource.value = newVideoUrl;
  
  // 更新 iframe 源
  const newIframeUrl = buildIframeUrl(currentUserId);
  iframeSource.value = newIframeUrl;
  
  // 等待 DOM 更新
  await nextTick();
  
  // 重新加载视频
  if (videoPlayer.value) {
    videoPlayer.value.load();
  }
  
  console.log('资源更新完成');
};

// 计算属性
const userId = computed(() => auth.getUserInfo().id);

const parkId = ref(null)
const parkData = ref([])
onMounted(async () => {
  loadEnterpriseData()
  fetchParkData()
  loadCardTtoal()
  initCharts()
  loadData()
  // 初始更新资源
  await updateResources();
});

//企业推荐信息
const enterpriseData = ref([])
const loadEnterpriseData = async () => {
  try {
    const resData = await request.get('/enterprise/getEnterprisePage', {
      params: {
        pageNum: 1,
        pageSize: 999,
        enterpriseIsFollowed: 'true'
      }
    })
    if (resData.success) {
      enterpriseData.value = resData.data.list
    }
  } catch (err) {

  } finally {
    // loading.close()
  }
}
const viewPageVisible = ref(false)
const currentEnterprise = ref(null);
// 点击事件处理函数
const handleItemClick = (item, index) => {
  console.log('点击了第', index + 1, '项', '企业信息：', item)
  viewPageVisible.value = true
  currentEnterprise.value = JSON.parse(JSON.stringify(item))
}

const handleViewPageClose = () => {
  viewPageVisible.value = false;
  currentEnterprise.value = null;
}


const fetchParkData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在初始化页面数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const myPartData = await request.get('park/page', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (myPartData.success) {
      // 假设后端返回格式：{ list: [...园区数据...], total: 100 }
      // 直接替换 parkData 的内容（保持响应式）
      // parkData.splice(0, parkData.length, ...data.list);
      // 同时将数据返回给子组件
      parkData.value = [...myPartData.data.list]
    }
  } catch (err) {
    parkData.value = []; // 出错时清空数据
  } finally {
    loading.close()
  }
}
// 核心KPI数据
const kpiData = ref({
  parkTotal: 0,//园区数
  spaceRate: 0,//空间利用率
  chargeTotal: 0,//收费总额
  arrearageTotal: 0,//欠费费总额
  enterprisePendingTotal: 0,//入住审核中：企业总数
  enterpriseApprovedTotal: 0,//入住已入住：企业总数
  enterpriseMovedOutTotal: 0,//入住已离园：企业总数
  signedContract: 0,//已签合同
  noSignedContract: 0//未签合同
});

const loadCardTtoal = async () => {
  const res = await request.get('dashboard/getData', {
    params: {
      parkId: parkId.value
    }
  })
  if (res.success) {
    kpiData.value.parkTotal = res.data.parkTotal

    kpiData.value.enterprisePendingTotal = res.data.enterprisePendingTotal == null ? 0 : res.data.enterprisePendingTotal
    kpiData.value.enterpriseApprovedTotal = res.data.enterpriseApprovedTotal == null ? 0 : res.data.enterpriseApprovedTotal
    kpiData.value.enterpriseMovedOutTotal = res.data.enterpriseMovedOutTotal == null ? 0 : res.data.enterpriseMovedOutTotal
    kpiData.value.signedContract = res.data.signedContract == null ? 0 : res.data.signedContract
    kpiData.value.noSignedContract = res.data.noSignedContract == null ? 0 : res.data.noSignedContract

    kpiData.value.spaceRate = res.data.spaceRate
    kpiData.value.chargeTotal = res.data.chargeTotal
    kpiData.value.arrearageTotal = res.data.arrearageTotal
  }
}

//点击全屏显示720云的iframe
const sevenTwoZeroIframe = ref(null)
const fullIframe = () => {
  const iframe = sevenTwoZeroIframe.value;
  if (iframe.requestFullscreen) {
    iframe.requestFullscreen().catch(err => {
      this.postMessageToIframe('fullscreen');
    });
  } else {
    this.postMessageToIframe('fullscreen');
  }
}
const occupancyChart = ref(null);
let occupancyInstance = null;
let spaceUsageInstance = null;
//园区入住统计
const spaceUsageChart = ref(null);
// 数据
const dashData = {
  // 园区管理模块数据
  occupancyData: {
    building: [''],
    rate: [0]
  },
  spaceUsageData: {
    categories: [''],
    usedArea: [0],
    idleArea: [0]
  },
};
const loadData = async () => {
  //查询园区入住
  try {
    const res = await request.get('dashboard/getEnterprise', {
      params: {
        parkId: parkId.value
      }
    })
    if (res.success) {
      dashData.occupancyData = res.data
    }
  } catch (error) {
    ElMessage.error("数据获取失败")
    console.error('获取数据失败:', error);
  }
  //空间使用率
  try {
    const spaceUsageData = await request.get('dashboard/getSpaceUsageData', {
      params: {
        parkId: parkId.value
      }
    })
    if (spaceUsageData.success) {
      dashData.spaceUsageData = spaceUsageData.data
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
  initChartsData()

}
// 初始化图表
const initCharts = () => {
  // 园区入驻率统计 - 柱状图
  occupancyInstance = echarts.init(occupancyChart.value);
  // 空间使用效率 - 堆叠柱状图
  spaceUsageInstance = echarts.init(spaceUsageChart.value);
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    occupancyInstance.resize();
    spaceUsageInstance.resize();
  });
};
const initChartsData = () => {
  occupancyInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dashData.occupancyData.building },
    yAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}' } },
    series: [{
      name: '入驻企业',
      type: 'bar',
      data: dashData.occupancyData.rate,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#409eff' },
          { offset: 1, color: '#6aa8ff' }
        ])
      }
    }]
  });

  spaceUsageInstance.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { data: ['已用面积', '空闲面积'], top: 'top' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dashData.spaceUsageData.categories },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} %' } },
    series: [
      { name: '已用面积', type: 'bar', stack: 'total', data: dashData.spaceUsageData.usedArea, itemStyle: { color: '#409eff' } },
      { name: '空闲面积', type: 'bar', stack: 'total', data: dashData.spaceUsageData.idleArea, itemStyle: { color: '#f56c6c' } }
    ]
  });
}


</script>

<style scoped>
.login-stats {
  position: absolute;
  top: 70px;
  left: 0;
  right: 0;
  padding: 0 20px;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  /* 核心：禁用指针事件，事件穿透到下方 */
  pointer-events: none;

  min-height: 100vh;
  /* 高度至少为视口高度 */
  box-sizing: border-box;
  /* 避免内边距导致溢出 */
}

.stat-cardleft {
  flex: 1;
  /* 平分宽度，可根据需求调整比例如flex: 0 0 50% */
  max-width: 300px;
  /* 限制最大宽度为50%，避免超出页面 */
  max-height: 90vh;
  /* 高度为视口高度 */
  overflow-y: auto;
  /* 内容超出时显示垂直滚动条 */

  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  /* 核心：恢复指针事件，使其可点击（不穿透） */
  pointer-events: auto;
}

.stat-cardright {
  flex: 1;
  /* 与左侧平分宽度 */
  max-width: 300px;
  /* 限制最大宽度为50%，避免超出页面 */
  height: 90vh;
  /* 高度为视口高度 */
  overflow-y: auto;
  /* 内容超出时显示垂直滚动条 */

  padding: 15px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  /* 核心：恢复指针事件，使其可点击（不穿透） */
  pointer-events: auto;
}

.stat-cardleft h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.stat-cardright h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  font-size: 14px;
}

.stat-item .value {
  font-weight: bold;
  color: #1890ff;
}

.chart-container {
  width: 265px;
  height: 200px;
}

.chart {
  width: 100%;
  height: 100%;
}

.elScroll {
  text-align: left;
  font-size: 15px;
  line-height: 25px;
}

/* 可选：添加点击反馈样式（如高亮） */
.elScroll li:hover {
  background-color: rgb(77, 199, 77);
  /* hover时背景色 */
}

.elScroll li:active {
  background-color: rgb(77, 199, 77);
  /* 点击时背景色 */
}
</style>